package com.chen.servicessepush.controller;

import com.chen.internalcommon.util.SsePrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.Map;

/**
 * 消息推送
 * @author chenLiuPing
 **/
@RestController
@Slf4j
public class SseController {
    private static Map<String, SseEmitter> sseEmitterMap = new HashMap<>();

    /**
     * 和接受消息推送的客户端进行连接
     */
    @GetMapping("/connect")
    public  SseEmitter connect(@RequestParam Long userId, @RequestParam String identity) {
        log.info("和用户id：{}, 用户类型:{}客户端进行连接", userId, identity);
        String sseKey = SsePrefixUtils.generateSseKey(userId, identity);
        // 过期时间永不过时
        SseEmitter sseEmitter = new SseEmitter(0L);
        sseEmitterMap.put(sseKey, sseEmitter);
        return sseEmitter;
    }

    /**
     * 给指定的客户端推送消息
     */
    @GetMapping("/push")
    public String push(@RequestParam Long userId, @RequestParam String identity, @RequestParam String content) {
        log.info("给用户:{}, 用户类型:{}推送消息", userId, identity);
        String sseKey = SsePrefixUtils.generateSseKey(userId, identity);
        try {
            if (sseEmitterMap.containsKey(sseKey)) {
                sseEmitterMap.get(sseKey).send(content);
            } else {
                return "推送失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "给用户:" + sseKey + " 推送了内容：" + content;
    }

    /**
     * 关闭和接受消息推送的客户端的连接
     */
    @GetMapping("/close")
    public String close(@RequestParam Long userId, @RequestParam String identity) {
        log.info("关闭用户id:{}, 用户类型:{}的连接", userId, identity);
        String sseKey = SsePrefixUtils.generateSseKey(userId, identity);
        sseEmitterMap.remove(sseKey);
        return "关闭成功";
    }
}
